<?php

namespace app\base\service;

use app\base\service\RedisService;
use think\admin\Service\AdminService;

define('TOKEN_KEY_PREFIX', 'token::res_user_id=');

/**
 * TOKEN服务
 * Class TokenService
 * @package think\admin\service
 */
class TokenService extends AdminService
{

    /**
     * 生成token字符串
     * @param string $user_id
     * @return string
     */
    function token_create($user_id){
        $char = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $max = strlen($char)-1;
        $token = '';
        for($i=0;$i<32;$i++){
            $token .= $char[rand(0, $max)];
        }
        return $token . sprintf('%08x', $user_id);
    }

    /**
     * 解析token字符串，成功返回用户id，失败返回false
     * @param string $str
     * @return number|boolean
     */
    function token_parse($str){
        if(strlen($str) == 40){
            return (int)hexdec(substr($str, -8));
        }
        return false;
    }

    /**
     * token对象放入memcache
     * @param int $user_id
     * @param TokenVo $token
     */
    function token_set($user_id, $token){
        $cache = RedisService::instance()->store();
        $key = TOKEN_KEY_PREFIX . $user_id;
        $cache->set($key, $token);
        $cache->expire($key, 72000000); 
        return true;
    }

    /**
     * 获取TokenVo对象
     * @param string $user_id
     */
    function token_get($user_id){
        $cache = RedisService::instance()->store();
        return ($user_id === false) ? false : $cache->get(TOKEN_KEY_PREFIX . $user_id);
    }

}